package respository

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/yyangl/yoyo/application"
	"github.com/yyangl/yoyo/models"
	"github.com/yyangl/yoyo/utils"
	"time"
)

const (
	cacheTime    = 3600
	menusCache   = "cache:admin:menus"
	promiseCache = "cache:admin:promise"
)

func CheckAccount(db *sql.DB, account, password string) (string, error) {
	id, pwd, err := models.GetAdminPassword(db, account)
	if err != nil {
		return "", err
	}
	if utils.Md5(password) != pwd {
		return "", errors.New("用户名密码不正确")
	}
	fmt.Printf("id is %d\n", id)
	token, err := utils.CreateToken(id, "admin")
	if err != nil {
		fmt.Printf("err %s", err.Error())
		return "", err
	}
	return token, nil
}

func CreateAccount(db *sql.DB, account, password, name string) error {
	pwd := utils.Md5(password)
	res, err := models.CreateAdmin(db, account, pwd, name)
	if err != nil {
		return err
	}
	if res {
		return nil
	}
	return errors.New("创建失败")
}

func GetPromiseByAdminID(s application.Service, uid int64) ([]models.Promise, error) {
	if s.Db() == nil {
		return nil, errors.New("databases is null")
	}
	var promises []models.Promise
	if s.Redis() != nil {
		res := s.Redis().Get(promiseCache).Val()
		fmt.Printf("redis string %s \n", res)
		if res != "" {
			err := json.Unmarshal([]byte(res), &promises)
			if err == nil {
				return promises, nil
			}
			fmt.Printf("json unmarshal error %v\n", err)
		}
	}
	promises, err := models.GetPromiseByAdminID(s.Db(), uid)
	if err != nil {
		return nil, err
	}
	go func() {
		bytes, err := json.Marshal(promises)
		if err != nil {
			return
		}
		s.Redis().Set(promiseCache, bytes, time.Duration(cacheTime+utils.Rand(120))*time.Second)
	}()
	return promises, nil
}
